package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFAnchor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.SubAreaService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("propotype")
public class SubAreaAction extends BaseAction<SubArea> {
	// 注入service
	@Autowired
	private SubAreaService subAreaService;
	@Action(value = "subArea_save", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/sub_area.html") })
	public String Save() {
		System.out.println(model);
		subAreaService.save(model);
		return SUCCESS;
	}

	// 执行有条件查询数据
	private Integer page;
	private Integer rows;

	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}
/*	@Action(value=("sub_area"),results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable =  new PageRequest(page-1,rows);
		Page<SubArea> page =subAreaService.findPageDate(pageable);
		//创建一个map集合将数据进行封装
		Map<String,Object> result = new  HashMap<String, Object>();
		result.put("total", page.getTotalElements());
		result.put("rows", page.getContent());
		//将map数据写到json数据当中来
		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}*/
	@Action(value = "sub_area", results = {@Result(name = "success", type = "json") })
	public String subAreafindall() {
		// 定义一个接收当前页数跟每页显示的数
		Pageable pageable = new PageRequest(page - 1, rows);
		System.out.println(model.getArea().getProvince());
		Specification<SubArea> specification = new Specification<SubArea>() {
			
			@Override
			public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// 定义一个集合来接收我们要查询的参数1
				List<Predicate> list = new ArrayList<Predicate>();
				Join<SubArea,Area> joins=root.join("area",JoinType.LEFT);
				if (StringUtils.isNotBlank(model.getArea().getProvince())) {
					Predicate p1 = cb.like(joins.get("province").as(String.class),
							"%" + model.getArea().getProvince() + "%");
					list.add(p1);
					System.out.println(p1);
				}
				if (StringUtils.isNotBlank(model.getArea().getCity())) {
					Predicate p2 = cb.like(joins.get("city").as(String.class), "%" + model.getArea().getCity() + "%");
					list.add(p2);
				}
				if (StringUtils.isNotBlank(model.getArea().getDistrict())) {
					Predicate p3 = cb.like(joins.get("district").as(String.class),
							"%" + model.getArea().getDistrict() + "%");
					list.add(p3);
				}
				Join<SubArea,FixedArea> join = root.join("fixedArea",JoinType.LEFT);
				if (StringUtils.isNotBlank(model.getFixedArea().getId())) {
					Predicate p4 = cb.like(join.get("id").as(String.class),
							"%" + model.getFixedArea().getId() + "%");
					list.add(p4);
				}
				if (StringUtils.isNotBlank(model.getKeyWords())) {
					Predicate p5 = cb.like(root.get("keyWords").as(String.class), "%" + model.getKeyWords() + "%");
					list.add(p5);
				}
				System.out.println(list);
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		//将数据发给service进行查询
		Page<SubArea> listSubArea = subAreaService.findalls(specification,pageable);
		//将数据转成我们想要的数据
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", listSubArea.getTotalElements());
		result.put("rows", listSubArea.getContent());
		System.out.println(result);
		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}
	//导入数据
	private File file;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
	@Action(value = "sub_area_import", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/sub_area.html") })
	public String sub_area_import() throws Exception{
		//建立一个list集合
		List<SubArea> listSubAreas = new ArrayList<SubArea>();
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
		
		for (Row row : sheetAt) {
			if(row.getRowNum()==0){
				continue;
			}
			if(row.getCell(0)==null||StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				continue;
			}
			SubArea subArea = new SubArea();
			subArea.setId(row.getCell(0).getStringCellValue());
			subArea.getFixedArea().setId(row.getCell(0).getStringCellValue());
//			FixedArea fixedArea = new FixedArea();
//			fixedArea.setId(row.getCell(1).getStringCellValue());
			subArea.getArea().setId(row.getCell(2).getStringCellValue());
//			Area area = new Area();
//			area.setId(row.getCell(2).getStringCellValue());
			subArea.setKeyWords(row.getCell(3).getStringCellValue());
			subArea.setStartNum(row.getCell(4).getStringCellValue());
			subArea.setEndNum(row.getCell(5).getStringCellValue());
			subArea.setSingle(row.getCell(6).getStringCellValue().toCharArray()[0]);
			subArea.setAssistKeyWords(row.getCell(7).getStringCellValue());
			listSubAreas.add(subArea);
		}
		subAreaService.saveSubAreas(listSubAreas);
		return SUCCESS;
	}
}
